'''
Created on Jul 2, 2011

@author: pau <boemianrapsodi@gmail.com>
'''

import os;
from xml.dom.minidom import Document;

class RepoFoldersManager:
    "A class used to manage folders into your personal repository"
    packetsFolder=None;
    repoList=None;
    
    def __init__(self, defaultPacketsFolder="../pkts"):
        self.packetsFolder=defaultPacketsFolder;
        try:
            self.CheckRepoStructure();
            print "RepoFoldersManager Created!";
        except Exception, error:
            print "Error: %s" % (error);
            os.mkdir(self.packetsFolder);
            print "created default packets folder %s" % (self.packetsFolder);
        self.UpdateRepoList();
        print "Packets List Updated!";
                
        
    def CheckRepoStructure(self):
        if os.path.isdir(self.packetsFolder)==False:
            raise Exception("Wrong packet folder given.");
    
    
    def UpdateRepoList(self):
        self.repoList = Document();
        root = self.repoList.createElement("LocalMarketPacketsList");
        self.repoList.appendChild(root);
        
        packetsSaved = os.listdir(self.packetsFolder);
        for packet in packetsSaved:
            if packet.endswith("apk"):
                packetNode = self.repoList.createElement("Packet");
                packetArray = packet.strip("apk").strip(".").split(" - ");
                packetName = self.repoList.createElement("PacketName");
                packetNameValue = self.repoList.createTextNode(packetArray[0]);
                packetName.appendChild(packetNameValue);
                packetNode.appendChild(packetName);
                packetVersion = self.repoList.createElement("PacketVersion");
                packetVersionValue = self.repoList.createTextNode(packetArray[1]);
                packetVersion.appendChild(packetVersionValue);
                packetNode.appendChild(packetVersion);
                packetLocation = self.repoList.createElement("PacketLocation");
                packetLocationValue = self.repoList.createTextNode(self.packetsFolder+"/"+packet);
                packetLocation.appendChild(packetLocationValue);
                packetNode.appendChild(packetLocation);
                root.appendChild(packetNode);
            
        loadedListFile = open(self.packetsFolder+"/packetsList.xml", "w");
        try:
            loadedListFile.write(self.repoList.toprettyxml(indent=""));
        finally:
            loadedListFile.close();
    
    
    def GetPacketsFolder(self):
        return self.packetsFolder;
    
    
    def GetRepoList(self):
        return self.repoList;

            
            